//
//  HRZSearchMainViewController.m
//  EMarket
//
//  Created by 石头 on 2018/5/31.
//  Copyright © 2018 好日子. All rights reserved.
//

#import "HRZSearchMainViewController.h"

// Controllers

// Models
#import "HRZSearchTagModel.h"
#import "HRZSearchTagSectionModel.h"
// Views
#import "HRZSearchCollectionViewCell.h"
#import "HRZSearchTagCollectionReusableView.h"
#import "HRZTextFileBgView.h"
// Vendors

// Categories

// Others
#import "HRZSearchTagLayout.h"
#import "HRZSearchTagManager.h"

#define CANCEL_VIEW_WIDTH  40
#define SEARCH_BAR_HEIGHT   30

static NSString * const HRZSearchCollectionViewCellID = @"HRZSearchCollectionViewCell";
static NSString * const HRZSearchTagCollectionReusableViewID = @"HRZSearchTagCollectionReusableView";


@interface HRZSearchMainViewController ()< UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate, HRZSearchCollectionViewCellDelegate, HRZSearchTagCollectionReusableViewDelegate>

@property (nonatomic, strong) UICollectionView *mCollection;

@property (nonatomic, strong) UITextField *searchTextField;
@property (nonatomic, strong) UIButton *rightClickView;

/**
 *  存储网络请求的热搜，与本地缓存的历史搜索model数组
 */
@property (nonatomic, strong) NSMutableArray *sectionArray;
/**
 *  存搜索的数组 字典
 */
@property (nonatomic,strong) NSMutableArray *searchArray;

@end

@implementation HRZSearchMainViewController

#pragma mark - LazyLoad
- (UITextField *)searchTextField{
    if (!_searchTextField) {
        HRZTextFileBgView *bgView = [[HRZTextFileBgView alloc] initWithFrame:CGRectMake(HRZMargin, 29, kScreenWidth - HRZMargin * 2 - 50, SEARCH_BAR_HEIGHT)];
        _searchTextField = [[UITextField alloc] initWithFrame:CGRectZero];
        
        UIImageView *leftImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_search"]];
        leftImage.frame = CGRectMake(7, 2, 15, 15);
        UIView * leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 22)];
        [leftView addSubview:leftImage];
        
        
        _searchTextField.leftView = leftView;
        _searchTextField.leftViewMode = UITextFieldViewModeAlways;
        
        bgView.backgroundColor = [UIColor clearColor];
        [bgView addSubview:_searchTextField];
        
        _searchTextField.frame = CGRectMake(0, 0, kScreenWidth - 2 * HRZMargin - 100, SEARCH_BAR_HEIGHT);
        _searchTextField.backgroundColor = [UIColor clearColor];
        _searchTextField.delegate = self;
        
        [self.view addSubview:bgView];
    }
    return _searchTextField;
}

- (UIButton *)rightClickView{
    if (!_rightClickView) {
        _rightClickView = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightClickView setTitle:@"取消" forState:UIControlStateNormal];
        [_rightClickView setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_rightClickView addTarget:self action:@selector(onCancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
        _rightClickView.frame = CGRectMake(kScreenWidth - HRZMargin - CANCEL_VIEW_WIDTH, 29, CANCEL_VIEW_WIDTH, SEARCH_BAR_HEIGHT);
        
        [self.view addSubview:_rightClickView];
    }
    return _rightClickView;
}

- (UICollectionView *)mCollection{
    if (!_mCollection) {
        HRZSearchTagLayout *layout = [[HRZSearchTagLayout alloc] init];
        
        _mCollection = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _mCollection.frame = CGRectMake(HRZMargin, HRZTopNavH, kScreenWidth - HRZMargin * 2, kScreenHeight - HRZTopNavH);
        [self.view addSubview:_mCollection];
        _mCollection.delegate = self;
        _mCollection.dataSource = self;
        
        /** 注册*/
        [_mCollection registerNib:[UINib nibWithNibName:NSStringFromClass([HRZSearchCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:HRZSearchCollectionViewCellID];
        
        [_mCollection registerClass:[HRZSearchTagCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HRZSearchTagCollectionReusableViewID];
    }
    return _mCollection;
}

- (NSMutableArray *)sectionArray{
    if (!_sectionArray) {
        _sectionArray = [[NSMutableArray alloc] init];
    }
    return _sectionArray;
}

- (NSMutableArray *)searchArray{
    if (!_searchArray) {
        _searchArray = [[NSMutableArray alloc] init];
    }
    return _searchArray;
}

#pragma mark - LifeCyle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setUpUI];
    
    [self setUpData];
}

#pragma mark - Base
/** Make UI */
- (void)setUpUI {
 
    self.mCollection.backgroundColor = [UIColor whiteColor];
    [self.rightClickView.titleLabel setFont:[UIFont systemFontOfSize:12]];
    [self.searchTextField becomeFirstResponder];

}


/** Make Data */
- (void)setUpData {
    /**
     *  测试数据 ，字段暂时 只用一个 titleString，后续可以根据需求 相应加入新的字段
     */
    NSDictionary *testDict = @{@"section_id":@"2",@"section_title":@"热搜",@"section_content":@[@{@"content_name":@"化妆棉"},@{@"content_name":@"面膜"},@{@"content_name":@"口红"},@{@"content_name":@"眼霜"},@{@"content_name":@"洗面奶"},@{@"content_name":@"防晒霜"},@{@"content_name":@"补水"},@{@"content_name":@"香水"},@{@"content_name":@"眉笔"}]};
    NSMutableArray *testArray = [@[] mutableCopy];
    [testArray addObject:testDict];
    
    /***  去数据查看 是否有数据*/
    NSDictionary *parmDict  = @{@"category":@"1"};
    NSDictionary *dbDictionary =  [[HRZSearchTagManager shareDefaultManager] statusesWithParams:parmDict];
    
    if (dbDictionary.count) {
        [testArray addObject:dbDictionary];
        [self.searchArray addObjectsFromArray:dbDictionary[@"section_content"]];
    }
    
    for (NSDictionary *sectionDict in testArray) {
        HRZSearchTagSectionModel *model = [[HRZSearchTagSectionModel alloc]initWithDictionary:sectionDict];
        [self.sectionArray addObject:model];
    }
    [_mCollection reloadData];
}

#pragma mark - Setting

#pragma mark - Getting


#pragma mark - -----------<Delegate>----------
#pragma mark - ----------  UICollectionViewDataSource  ----------
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    HRZSearchTagSectionModel *sectionModel = self.sectionArray[section];
    return sectionModel.section_contentArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HRZSearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:HRZSearchCollectionViewCellID forIndexPath:indexPath];
    
    HRZSearchTagSectionModel *sectionModel = self.sectionArray[indexPath.section];
    HRZSearchTagModel *tagModel = sectionModel.section_contentArray[indexPath.row];
    [cell.contentButton setTitle:tagModel.content_name forState:UIControlStateNormal];
    cell.delegate = self;
    
    return cell;
}

#pragma mark - ----------  UICollectionViewDelegate  ----------
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.sectionArray.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableView = nil;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        HRZSearchTagCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:HRZSearchTagCollectionReusableViewID forIndexPath:indexPath];
        view.delegate = self;
        HRZSearchTagSectionModel *sectionModel = self.sectionArray[indexPath.section];
        [view setText:sectionModel.section_title];
        if(indexPath.section == 0)
        {
            [view setImage:@"icon_hot"];
            view.delectButton.hidden = YES;
        }else{
            [view setImage:@"icon_search"];
            view.delectButton.hidden = NO;
        }
        reusableView = view;
    }
    return reusableView;
}

- (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HRZSearchTagSectionModel *sectionModel =  self.sectionArray[indexPath.section];
    if (sectionModel.section_contentArray.count > 0) {
        HRZSearchTagModel *contentModel = sectionModel.section_contentArray[indexPath.row];
        return [HRZSearchCollectionViewCell getSizeWithText:contentModel.content_name];
    }
    return CGSizeMake(80, 24);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
}

#pragma mark - ----------  HRZSearchCollectionViewCellDelegate  ----------
- (void)selectButtonClick:(HRZSearchCollectionViewCell *)cell {
    NSIndexPath *indexPath = [self.mCollection indexPathForCell:cell];
    HRZSearchTagSectionModel *sectionModel = self.sectionArray[indexPath.section];
    HRZSearchTagModel *tagModel = sectionModel.section_contentArray[indexPath.row];
    
    UIAlertView *al = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"搜索 %@ 的相关内容",tagModel.content_name] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"知道了！", nil];
    [al show];
}
#pragma mark - ----------  HRZSearchTagCollectionReusableViewDelegate  ----------
- (void)delectData:(HRZSearchTagCollectionReusableView *)view
{
    if (self.sectionArray.count > 1) {
        [self.sectionArray removeLastObject];
        [self.searchArray removeAllObjects];
        [self.mCollection reloadData];
        [[HRZSearchTagManager shareDefaultManager] saveStatuses:@{} andParam:@{@"category":@"1"}];
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""]){
        return NO;
    }
    /***  每搜索一次   就会存放一次到历史记录，但不存重复的*/
    if ([self.searchArray containsObject:[NSDictionary dictionaryWithObject:textField.text forKey:@"content_name"]]) {
        return YES;
    }
    [self reloadData:textField.text];
    return YES;
}
- (void)reloadData:(NSString *)textString
{
    [self.searchArray addObject:[NSDictionary dictionaryWithObject:textString forKey:@"content_name"]];
    
    NSDictionary *searchDict = @{@"section_id":@"1",@"section_title":@"历史记录",@"section_content":self.searchArray};
    
    /***由于数据量并不大 这样每次存入再删除没问题  存数据库*/
    NSDictionary *parmDict  = @{@"category":@"1"};
    [[HRZSearchTagManager shareDefaultManager] saveStatuses:searchDict andParam:parmDict];
    
    HRZSearchTagSectionModel *model = [[HRZSearchTagSectionModel alloc] initWithDictionary:searchDict];
    if (self.sectionArray.count > 1) {
        [self.sectionArray removeLastObject];
    }
    [self.sectionArray addObject:model];
    [self.mCollection reloadData];
//    self.cxSearchTextField.text = @"";
}
#pragma mark - scrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    [self.cxSearchTextField resignFirstResponder];
}

#pragma mark - ----------  UISearchBarDelegate  ----------
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = YES;
    for(UIView *view in  [[[searchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            UIButton * cancel =(UIButton *)view;
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
            cancel.titleLabel.font = [UIFont systemFontOfSize:14];
            cancel.tintColor = [UIColor darkGrayColor];
        }
    }
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.searchTextField resignFirstResponder];
}

#pragma mark - ----------  Action  ----------
- (void)onCancelBtnClick {
    [self.navigationController popViewControllerAnimated:NO];
}

@end
